global with sharing class batchInstagramLikes implements Database.Batchable<sObject>, Database.AllowsCallouts {
    
    global final String query;
    
    global batchInstagramLikes() { 
            datetime dt = datetime.now();
            String formatedDt = dt.format('yyyy-MM-dd\'T\'HH:mm:ss\'Z\'');//format the datetime to make it Dynamic Soql ready
            query = 'Select Id, Media_Id__c From Instagram_Conversation__c where Media_Id__c != null and (Next_API_Callout_Datetime__c = null OR Next_API_Callout_Datetime__c < ' + formatedDt + ')';                      
            //query = q; 
    }
    
    global Database.Querylocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(query);
    }
        
    
    global void execute(Database.BatchableContext BC, List<Sobject> scope) {
            //get token
            Instagram_Token__c token = [SELECT Access_Token__c, Client_Id__c, User_Id__c FROM Instagram_Token__c LIMIT 1]; 
            string access_token = token.Access_Token__c;
        
        
            for(Sobject so : scope) {
                Instagram_Conversation__c insta = (Instagram_Conversation__c)so;
                globalInstagramPost.postSchedLikeServiceRequest(insta.media_id__c, access_token); 
                //make the call out  
            }
            
    }
    
    global void finish(Database.BatchableContext BC){
        AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems,
        CreatedBy.Email FROM AsyncApexJob WHERE Id=:BC.getJobId()];
        
        //Send an email to the apex job submitter
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {'porquillo@cloudconceptgroup.com'};
        mail.setToAddresses(toAddresses);
        mail.setSubject('Instagram Records : ' + a.Status);
        mail.setPlainTextBody('The Instagram Likes Apex job processed ' + a.TotalJobItems + ' batch(es) with ' + a.NumberOfErrors + ' failures');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        
    }
    

}